'use strict';
const { Op } = require('sequelize');
module.exports = app => {
  class Conversation extends app.Service {
    async createConversation(userId, staffId) { // 创建一个会话，并且跟工单和会话列表相关联
      try {
        const conversation = await app.model.Conversation.create({ user_id: Number(userId), staff_id: Number(staffId) });
        return conversation;
      } catch (e) {
        return null;
      }
    }

    // 更新最新一条信息
    async setNewsContent(id, content, contentType) {
      try {
        let conversation;
        if (Number(contentType) === 2) {
          conversation = await app.model.Conversation.update({ news_content: '图片' }, { where: { id } });
        } else {
          conversation = await app.model.Conversation.update({ news_content: content }, { where: { id } });
        }
        return conversation;
      } catch (e) {
        return null;
      }
    }

    async getConversationList(user, filterObj) {
      const ctx = this.ctx;
      const result = await app.model.Conversation.findAll({ order: [[ 'created_at', 'DESC' ]], where: filterObj });

      const { permission } = user;
      const conversationList = [];

      const handleListItem = async index => {
        const item = result[index];
        if (item.type === 1 && permission === 3) return;
        const { user_id, staff_id, news_content, id } = item;
        const user_info = await ctx.service.user.getUserById(user_id);
        const another_user_info = await ctx.service.user.getUserById(staff_id);

        const listItem = {
          conversation_id: id,
          user_info,
          user_id,
          staff_id,
          type: item.type,
          another_user_info,
          news_content,
          created_at: user_info.createdAt,
        };

        conversationList.push(listItem);
      };

      if (result.length) {
        for (let i = 0; i < result.length; i++) {
          await handleListItem(i);
        }
      }

      if (!conversationList.length) {
        const defaultConversation = await ctx.service.conversation.getConversationById(0);
        conversationList.push(defaultConversation);
      }

      return conversationList;
    }

    async getConversationByUserId(userId, staffId, notEnd = true) {
      try {
        const conversation = await app.model.Conversation.findOne(
          {
            where: {
              user_id: Number(userId),
              staff_id: Number(staffId),
              [Op.not]: [
                notEnd ? { type: 1 } : {},
              ],
            },
          }
        );
        return conversation;
      } catch (e) {
        return null;
      }
    }

    async getConversationById(conversationId) {
      const ctx = this.ctx;
      const token = ctx.request.header.token;
      const decode = ctx.app.jwt.verify(token, ctx.app.config.jwt.secret);
      try {

        if (Number(conversationId) === 0) {
          const baseStaffId = ctx.state.baseStaffId;
          const baseStaff = await ctx.service.user.getUserById(baseStaffId);
          const user = await ctx.service.user.getUserByName(decode.username);
          return {
            conversation_id: 0,
            user_info: user, // 普通用户
            user_id: user.id,
            staff_id: baseStaffId,
            another_user_info: baseStaff, // 基础客服的信息
            created_at: user.createdAt,
          };
        }
        const conversation = await app.model.Conversation.findOne({ where: { id: conversationId } });
        const { user_id, staff_id, news_content, id, type } = conversation;
        const user_info = await ctx.service.user.getUserById(user_id);
        const another_user_info = await ctx.service.user.getUserById(staff_id);

        const result = {
          conversation_id: id,
          user_info,
          user_id,
          staff_id,
          type,
          another_user_info,
          news_content,
          created_at: user_info.createdAt,
        };

        return result;
      } catch (e) {
        return null;
      }

    }

    async setConversationStaff(conversationId, staffId) {
      try {
        await app.model.Conversation.update({ staff_id: staffId, type: 2 }, { where: { id: conversationId } });
      } catch (e) {
        return null;
      }
    }

    async endTicket(conversationId) {
      try {
        const result = await app.model.Conversation.update({ type: 1 }, { where: { id: conversationId } });
        return result;
      } catch (e) {
        return null;
      }
    }

    async evaluate(conversationId, score) {
      try {
        const result = await app.model.Conversation.update({ score }, { where: { id: conversationId } });
        return result;
      } catch (e) {
        return null;
      }
    }

  }
  return Conversation;
};
